/*
 * This file is part of the eccOS Library.
 * Copyright (C) 2007.
 *
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 */
package org.openeccos.util;

import java.io.File;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import nextapp.echo2.app.ApplicationInstance;
import nextapp.echo2.app.Command;
import nextapp.echo2.app.ImageReference;
import nextapp.echo2.app.ResourceImageReference;
import nextapp.echo2.webcontainer.command.BrowserOpenWindowCommand;

import org.openeccos.DownloadServlet;
import org.openeccos.EccosAppInstance;
import org.openeccos.DownloadServlet.Document;

import echopointng.xhtml.XhtmlFragment;

public class PDUtil {

	private static final char[] arrayChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	public static final String PDF_CONTENT_TYPE = "application/pdf";
	public static final String XLS_CONTENT_TYPE = "application/xls";
	public static Map<String, ImageReference> imageReferenceMap = new HashMap<String, ImageReference>();

	public static Object[] addEmpty(Object[] src) {
		Object[] values = new Object[src.length + 1];
		System.arraycopy(src, 0, values, 1, src.length);
		values[0] = "";
		return values;
	}

	public static String createLogin(int charCount) {
		StringBuilder login = new StringBuilder();
		Random r = new Random();
		for (int i = 0; i < charCount; i++) {
			if (i % 3 == 0 && i != 0) {
				login.append('-');
			}
			login.append(arrayChars[r.nextInt(arrayChars.length)]);
		}
		return login.toString();
	}

	public static void doDownload(final byte[] content, final String fileName, final String contentType) {
		Document doc = new Document();
		doc.setId(new Random().nextInt() + "");
		doc.setContentLength(content.length);
		doc.setContents(content);
		doc.setMimeType(contentType);
		doc.setName(fileName);
		DownloadServlet.addDocument(doc);
		
        String uri = "download?docId=" + doc.getId();        
        Command command = new BrowserOpenWindowCommand(uri, fileName, "width=800,height=600,resizable=yes");
        ApplicationInstance.getActive().enqueueCommand(command);
        
//        PDWindowPane wnd = new PDWindowPane() {};
//        wnd.setTitle(fileName);
//        wnd.add(new HttpPaneEx(uri));
//        wnd.setWidth(new Extent(700));
//        wnd.setHeight(new Extent(600));
//        EccosDesktop.getDesktop().addWindow(wnd);
	}

	public static String emptyString(String s) {
		return s == null ? "(Empty)" : s;
	}

	public static Calendar getCalendar(int d, int m, int y) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, d);
		cal.set(Calendar.MONTH, m);
		cal.set(Calendar.YEAR, y);
		return cal;
	}

	public static XhtmlFragment getXHTML(String text) {

		boolean isIE = ((EccosAppInstance) ApplicationInstance.getActive()).isIE();

		String xhtml = null;
		if (isIE) {
			text = text.replaceAll("<big>", "<font size=\"4\">");
			text = text.replaceAll("</big>", "</font>");
			xhtml = "<p align=\"justify\">" + text + "</p>";
		} else {
			text = text.replaceAll("<a href", "<xhtml:a href");
			text = text.replaceAll("</a>", "</xhtml:a>");
			text = text.replaceAll("<i>", "<xhtml:i>");
			text = text.replaceAll("</i>", "</xhtml:i>");
			text = text.replaceAll("<tt>", "<xhtml:tt>");
			text = text.replaceAll("</tt>", "</xhtml:tt>");
			text = text.replaceAll("<pre>", "<xhtml:pre>");
			text = text.replaceAll("</pre>", "</xhtml:pre>");
			text = text.replaceAll("<b>", "<xhtml:b>");
			text = text.replaceAll("</b>", "</xhtml:b>");
			text = text.replaceAll("<hr/>", "<xhtml:hr/>");
			text = text.replaceAll("<br/>", "<xhtml:br/>");
			text = text.replaceAll("<p ", "<xhtml:p ");
			text = text.replaceAll("</p>", "</xhtml:p>");
			text = text.replaceAll("<p/>", "<xhtml:p/>");
			text = text.replaceAll("<big>", "<xhtml:font size=\"4\">");
			text = text.replaceAll("</big>", "</xhtml:font>");
			xhtml = "<span xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"> <xhtml:p style=\"text-align: justify\">";
			xhtml += text;
			xhtml += "</xhtml:p> </span>";
		}
		return new XhtmlFragment(xhtml);
	}

	public static boolean isBefore(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		cal1.set(Calendar.HOUR, 0);
		cal1.set(Calendar.MINUTE, 0);
		cal1.set(Calendar.SECOND, 0);
		Calendar cal2 = Calendar.getInstance();
		cal1.setTime(date1);
		cal1.set(Calendar.HOUR, 0);
		cal1.set(Calendar.MINUTE, 0);
		cal1.set(Calendar.SECOND, 0);
		return cal1.before(cal2);
	}

	public static boolean isEmpty(Object o) {
		if (o == null) return true;
		return o.toString().trim().length() == 0;
	}

	/**
	 * The base path of the application
	 * In a deployed environment this would be:
	 * $CATALINA_BASE/name_of_application
	 */
	public File getBasePath() {
		return null;
	}

	public static ImageReference getImage(String name) {
		String key = ImageReference.class.getName() + ":" + name;
		ImageReference img = imageReferenceMap.get(key);
		if (img == null) {
			img = new ResourceImageReference(name);
			imageReferenceMap.put(key, img);
		}
		return img;
	}

	public static int[] htmlColorToIntRGBArray(String str) throws ParseException {
		if (str == null) {
			throw new NullPointerException("str == null");
		}

		str = str.trim();

		if (str.length() != 7) {
			throw new ParseException("str.length() != 7", 0);
		}

		if (!str.startsWith("#")) {
			throw new ParseException("!str.startsWith(\"#\")", 0);
		}

		int[] ret = new int[3];

		ret[0] = Integer.parseInt(str.substring(1, 3), 16);
		ret[1] = Integer.parseInt(str.substring(3, 5), 16);
		ret[2] = Integer.parseInt(str.substring(5, 7), 16);

		return ret;
	}

	public static String intRGBArrayToHtmlColor(int[] rgbArray) {
		if (rgbArray == null) {
			throw new NullPointerException("rgbArray == null");
		}

		if (rgbArray.length != 3) {
			throw new IllegalArgumentException("rgbArray.length != 3");
		}

		StringBuffer ret = new StringBuffer("#");

		for (int i = 0; i < 3; i++) {
			String curr = Integer.toHexString(rgbArray[i]);

			if (curr.length() == 1) {
				ret.append("0");
			}

			ret.append(curr);
		}

		return ret.toString();
	}
}
